package filelist

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"strings"
)

const PREFIX = "/list/"

type userError string

func (e userError) Error () string {
	return e.Message()
}

func (e userError) Message() string {
	return string(e)
}

func FileHandlerList(writer http.ResponseWriter, request *http.Request) error {
	// 防止其他路由出现报错
	if strings.Index(request.URL.Path, PREFIX) != 0 {
		return userError("path must start" +  "with" + PREFIX)
	}

	path := request.URL.Path[len(PREFIX):]
	fmt.Println()
	file, err := os.Open(path)
	defer file.Close()

	if err != nil {
		// 直接报错挂掉，但是http 会捕获错误不会让程序挂掉
		//panic(err.Error())
		//return

		// 改进
		//http.Error(writer, err.Error(), http.StatusInternalServerError)

	    // 改进 3
		return err
	}


	all, err := ioutil.ReadAll(file)
	if err != nil {
		return err
	}

	writer.Write(all)
	return nil
}